﻿using DGIS.Control.系统管理;
using DGIS.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DGIS.Map.Pages
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow1 : Window
    {
        DGIS.Control.GsUserControl _gsUserControl = new Control.GsUserControl();
        private string captchaCode;

        public LoginWindow1()
        {
            try
            {
                //实例化CookieContainer
                AppConstant.CookieContainer = new System.Net.CookieContainer();

                InitializeComponent();

                Init();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace + ";" + ex.Message);
            }

        }

        //用户名
        private string _userName;
        //密码
        private string _psw;
        //验证码
        private string _validateCode;

        #region 事件

        //键盘事件
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                AutoLogin_Click(null, null);
        }

        //拖拽
        private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                this.DragMove();
            }
            catch (Exception)
            {

            }
        }

        //关闭
        private void Close_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Environment.Exit(0);
        }

        //登录
        private void Login_Click(object sender, RoutedEventArgs e)
        {
            ShowProgressBar(true);
            _userName = this.UserNameText.Text.Trim();
            if (string.IsNullOrEmpty(_userName))
            {
                MessageBox.Show("请输入用户名");
                return;
            }
            _psw = this.PswText.Password.Trim();
            _validateCode = this.ValidateCode.Text.Trim();

            Task.Run(() =>
            {
                Login();
            }).ContinueWith((x) => { x.Dispose(); });
        }

        private void AutoLogin_Click(object sender, RoutedEventArgs e)
        {
            ShowProgressBar(true);
            _userName ="";
            _psw = "";
            _validateCode = this.ValidateCode.Text.Trim();

            Task.Run(() =>
            {
                Login();
            }).ContinueWith((x) => { x.Dispose(); });
        }


        private void ValidateImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ChangeValidateCode();
        }

        /// <summary>
        /// 手动更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateTxt_MouseDown(object sender, MouseButtonEventArgs e)
        {
            SysControl sysControl = new SysControl();
            string url = sysControl.CheckSysUpdate();

            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("没有检测到新版本");
            }
            else
            {
                Process.Start(url);
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            //加载默认用户信息
            List<GSUser> items = _gsUserControl.GetDBUserList();
            if (items.Any(x => x.Type == 1))
            {
                GSUser user = items.FirstOrDefault(x => x.Type ==1);

                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.UserNameText.Text = user.UserName;
                    //this.PswText.Password = user.Psw;
                }));
            }

            //清空缓存
            string cacheFolder = string.Format("{0}Cache",AppDomain.CurrentDomain.BaseDirectory);
            string[] files = System.IO.Directory.GetFiles(cacheFolder);
            for (int i = 0; i < files.Length; i++)
            {
                System.IO.File.Delete(files[i]);
            }

            //显示验证码
            ChangeValidateCode();
        }

        /// <summary>
        /// 更换验证码
        /// </summary>
        private void ChangeValidateCode()
        {
            this.ValidateCode.Clear();
            AppConstant.CookieContainer = new System.Net.CookieContainer();
            Task.Run(() =>
            {
                //获取基本信息
                BitmapImage bitmap = null;
                Stream stream = _gsUserControl.GetLoginValidateImg(ref AppConstant.CookieContainer,out captchaCode);
                if (stream == null)
                {
                    bitmap = new BitmapImage(new Uri(string.Format("{0}Images//pause.png", AppDomain.CurrentDomain.BaseDirectory)));
                }
                else
                {
                    bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = stream;
                    bitmap.EndInit();
                }
                this.ValidateImg.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.ValidateImg.Source = bitmap;

                }));
            }).ContinueWith(x=>x.Dispose());            
        }

        /// <summary>
        /// 验证码检测
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private bool CheackValidate(string code)
        {
            return _gsUserControl.CheackValidate(code, captchaCode, ref AppConstant.CookieContainer);
        }

        /// <summary>
        /// 登录（多线程执行方法）
        /// </summary>
        private void Login()
        {
            GSUser item = null;
            //if (CheackValidate(_validateCode))
            if (true)
            {
                int resultCode;
                item = _gsUserControl.LoginWeb(_userName, _psw, captchaCode, _validateCode.ToUpper(), ref AppConstant.CookieContainer,out resultCode);
                this.Dispatcher.Invoke(new Action(() =>
                {
                    ShowProgressBar(false);

                    switch (resultCode)
                    {
                        case 1:
                            this.Hide();

                            MainWindow frm = new MainWindow(item);
                            frm.Show();
                            break;
                        case -100:
                            ChangeValidateCode();
                            MessageBox.Show("登录失败，您也可以不输入账号密码直接匿名登录");
                            break;
                        case -3:
                            ChangeValidateCode();
                            MessageBox.Show("验证码输入有误");                            
                            break;
                        default:
                            ChangeValidateCode();
                            break;
                    }
                }));
            }

        }

        /// <summary>
        /// 进度条控制
        /// </summary>
        /// <param name="show"></param>
        private void ShowProgressBar(bool show)
        {
            this.ProgressBar.Visibility = show ? Visibility.Visible : Visibility.Hidden;
            this.UserNameText.IsEnabled = !show;
            this.PswText.IsEnabled = !show;
            this.LoginBtn.IsEnabled = !show;
        }

        #endregion

        
    }
}
